package com.onepiece.shipelves.common.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author wangxj
 * @Desc: 集合util
 * @date 2019-10-17
 */
public class CollectionUtil {

    /**
     * 将某个集合转换为Stirng
     *
     * @param collection
     * @return
     */
    public static String collectionToString(Collection collection) {
        if (!CollectionUtils.isEmpty(collection)) {
            StringBuilder result = new StringBuilder();
            for (Object o : collection) {
                if (!StringUtils.isEmpty(result.toString())) {
                    result.append(",");
                }
                result.append(o.toString());
            }
            return result.toString();
        }
        return "";
    }

    /**
     * 将以 ，分隔的字符串转换成集合
     *
     * @param s
     * @return
     */
    public static List<String> stringToList(String s) {

        if (StringUtils.isEmpty(s)) {
            return new ArrayList<>();
        } else if (s.contains(",")) {
            String[] split = s.split(",");
            return Arrays.asList(split);
        } else {
            ArrayList<String> strings = new ArrayList<>();
            strings.add(s);
            return strings;
        }
    }

    /**
     * list<String> to list<object>
     *
     * @param text
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> parseList(List<String> text, Class<T> clazz) {
        ArrayList<T> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(text)) {
            return list;
        }
        for (String s : text) {
            T t = JSON.parseObject(s, clazz);
            list.add(t);
        }
        return list;
    }

    /**
     * 将listAll里面索引对应的值相加
     * listAll.item.size = size
     *
     * @param listAll
     * @param size
     * @return
     */
    public static List<Integer> addListIndexValue(List<List<Integer>> listAll, Integer size) {
        List<Integer> result = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            int value = 0;
            for (List<Integer> list : listAll) {
                if (list.size() < size) continue;
                value += list.get(i);
            }
            result.add(value);
        }
        return result;
    }


}
